package com.lq.schoolshop.controller.before;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lq.schoolshop.bean.Result;
import com.lq.schoolshop.bean.StatusCode;
import com.lq.schoolshop.controller.BaseController;
import com.lq.schoolshop.pojo.User;
import com.lq.schoolshop.service.UserService;
import com.lq.schoolshop.util.DESUtil;
import com.lq.schoolshop.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @Author
 * @Date2021/1/4 10:55
 * @Version V1.0
 * 功能定位：前台
 * 功能描述：用户信息管理
 **/
@Api(value = "商城前台功能--用户模块",tags = "商城前台功能--用户模块")
//@CrossOrigin(origins = "*",maxAge = 3600)
@Controller
@RequestMapping(value = "before")
public class ForUserController extends BaseController {

    private  final  String  keys = "88975522212";  //私钥
    private Logger logger = Logger.getLogger(ForUserController.class);

    @Autowired
    private UserService userService;

    //1.动态加载logo头像
    @ApiOperation(value = "加载头像",notes = "用来加载登录头像")
    @ApiImplicitParam(name = "name",value = "用户账号",dataType = "String",required = true,paramType = "query")
    @ResponseBody
    @RequestMapping(value = "/loadlogoimg",method = RequestMethod.GET)
    public Result loadLogoImg(HttpServletRequest request, HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin","*");
        String name = request.getParameter("name");
        String nameimg = userService.getlogoImg(name);
        Result result = null;
        if(nameimg!=null){
            result = new Result(true, StatusCode.OK,"用户头像加载成功",nameimg);
        }else{
            result = new Result<>(false, StatusCode.NotSource,"头像资源找不到");
        }
        return result;
    }

    //2.用户注册
    @ApiOperation(value = "用户注册",notes = "用户根据账号密码注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username",value = "用户账号",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "password",value = "用户密码",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "name",value = "用户姓名",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "sex",value = "用户性别",dataType = "String",paramType = "query"),
    })
    @ResponseBody
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public Result register(HttpServletResponse response,  @RequestParam(name = "username") String username ,
                           @RequestParam(name = "password") String password,
                           @RequestParam(name = "name")String name,
                           @RequestParam(name = "sex") String sex ){
        response.setHeader("Access-Control-Allow-Origin","*");
        String uuidrandom = UUID.randomUUID().toString();
        Result result =null;
        int exist = userService.exist(username);
        System.out.println("exist:"+exist);
        if(exist>0){
            //用户存在
            result = new Result(false,StatusCode.ERROR,"用户名已经存在");
        }else{
            //用户不存在
            Md5Hash md5Hash = new Md5Hash(password, "lq", 1);
            int regislogi = userService.regislogi(sex,username, md5Hash.toString(), name, uuidrandom);
            if(regislogi>0){
                //注册成功
                result = new Result(true,StatusCode.OK,"注册成功");
            }else{
                //注册失败
                result = new Result(false,StatusCode.ERROR,"注册失败");
            }
        }
        return result;
    }

    //3.用户登录
    @ApiOperation(value = "用户登录",notes = "首页登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username",value = "用户账号",dataType = "String",required = true,paramType = "query"),
            @ApiImplicitParam(name = "password",value = "用户密码",dataType = "String",required = true,paramType = "query")
    })
    @ResponseBody
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result Userlogin(HttpServletResponse response,@RequestParam(name = "username") String username , @RequestParam(name = "password") String password){
        response.setHeader("Access-Control-Allow-Origin","*");
        Result result = null;
        User ResultUser = new User();
        //1.获取Subject
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("name", username);
        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //3.执行登录方法
        try {
            subject.login(token);
            User userAll =  (User)session.getAttribute("user");
            ResultUser.setId(userAll.getId());
            ResultUser.setName(userAll.getName());
            ResultUser.setUsername(userAll.getUsername());
            ResultUser.setIcon(userAll.getIcon());
            ResultUser.setSecretkey(userAll.getSecretkey());
            ResultUser.setStatus(userAll.getStatus());
            String resultUser = JSONObject.toJSONString(ResultUser);

            String tokensign = JwtUtil.sign(resultUser, String.valueOf(userAll.getId()));

            int updatetoken = userService.updatetoken(userAll.getId(), tokensign);
            System.out.println("登录之后 更改的update:"+updatetoken);
            if(userAll.getStatus().equals("开启")) {
                logger.info("用户:"+userAll.getUsername()+"-成功登陆");
                result = new Result(true,StatusCode.OK,"登录成功",tokensign);
            }else{
                result = new Result(true,StatusCode.FREEZEERROR,"账户冻结",tokensign);
            }
        } catch (UnknownAccountException e) {
            result = new Result(false,StatusCode.ERROR,"账号或密码错误");
        } catch (IncorrectCredentialsException e) {
            result = new Result(false,StatusCode.ERROR,"账号或密码错误");
        } catch (LockedAccountException e) {
            result = new Result(false,StatusCode.ERROR,"账户被冻结");
        }
        return result;
    }


    //4.申诉
    @ApiOperation(value = "账号申诉-验证密钥",notes = "进行账号的申诉更改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username",value = "用户账号",dataType = "String",required = true,paramType = "query"),
            @ApiImplicitParam(name = "uuid",value = "申诉密钥",dataType = "String",required = true,paramType = "query"),
    })
    @RequestMapping(value = "/complain",method = RequestMethod.POST)
    @ResponseBody
    public Result complain(HttpServletResponse response ,@RequestParam("username") String username,@RequestParam("uuid") String uuid){
        response.setHeader("Access-Control-Allow-Origin","*");
        Result result = null;
        String uuidrandom = UUID.randomUUID().toString();
        int complain = userService.complain(username, uuid);
        if (complain>0){
            //有该用户 可以进行更改
            int i = userService.updateByUUID(uuidrandom, username);
            System.out.println("修改申诉后的UUID："+i);
            Md5Hash md5Hash = new Md5Hash(username,uuid, 1);
            byte[] encrypt = DESUtil.encrypt(username, keys);
            String encryptResultStr = DESUtil.parseByte2HexStr(encrypt);
            System.out.println("*****************加密后***************：" + encryptResultStr);
            baseinfolog("用户模块","忘记密码账号申诉",i);
            result = new Result(true,StatusCode.OK,"客服验签成功",encryptResultStr);
        }else{
            //没有该用户 不能更改
            baseerrorlog("用户模块","忘记密码账号申诉","客服验签失败");
            result = new Result(false,StatusCode.ERROR,"客服验签失败");
        }
        return result;
    }

    //4.1申诉
    @ApiOperation(value = "账号申诉-正式申诉",notes = "进行申诉后的密码修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "newpassword",value = "修改密码",dataType = "String",required = true,paramType = "query"),
            @ApiImplicitParam(name = "key",value = "密钥",dataType = "String",required = true,paramType = "query")
    })
    @RequestMapping(value = "/complainFinally",method = RequestMethod.POST)
    @ResponseBody
    public Result complainFinally(HttpServletResponse response ,@RequestParam("newpassword")String newpassword,@RequestParam("key") String key){
        response.setHeader("Access-Control-Allow-Origin","*");
        Result result = null;
        System.out.println("******************收到密钥********:"+key);
        byte[] decryptFrom = DESUtil.parseHexStr2Byte(key);
        byte[] decryptResult =DESUtil.decrypt(decryptFrom,keys);
        System.out.println("解密后：" + new String(decryptResult));
        String user = new String(decryptResult);
        Md5Hash pwdmd5 = new Md5Hash(newpassword,"lq", 1);
        int i = userService.updatePwdByname(user, pwdmd5.toString());
        if(i>0){
            //根据用户名修改密码
            result = new Result(true,StatusCode.OK,"申诉成功");
            baseinfolog("用户模块","密码更改","受影响行数:"+result);
            //重新封装Token

        }else{
            //密钥不一致 失败
            result = new Result(false,StatusCode.ERROR,"申诉失败");
            baseerrorlog("用户模块","密码更改","密码更改失败");
        }
        return result;
    }


    //4.3 Token验证
    @ApiOperation(value = "Token验证",notes = "进行Token验证是否成功")
    @RequestMapping(value = "/VerifyToken",method = RequestMethod.GET)
    @ResponseBody
    public Result VerifyToken(){
        Result result = new Result(true,StatusCode.OK,"身份信息验证成功");
        return result;
    }








}
